import $ from '@/assets/js/jquery-vendor.js'
import layer from '#/layer/layer.min.js'
import plupload from 'plupload'
import {getFileServerJoinContextPath} from './boss';

window.upload_single_file = function (btn, divId, _fileExt, name, callback) {
  var fileMaxSize = 50;
  var fileExtensions = _fileExt || 'doc';
  var uploader = new plupload.Uploader({
    runtimes: 'html5,flash,silverlight,html4',
    browse_button: '' + btn,
    multi_selection: false,
    container: document.getElementById('' + divId),
    url: window.uploadPath + '/file/fileUpload?dir=file',

    filters: {
      mime_types: [
        {title: 'all files', extensions: fileExtensions}
      ],
      max_file_size: fileMaxSize + 'mb', // 最大只能上传mb的文件
      prevent_duplicates: false // 不允许选取重复文件
    },

    init: {
      PostInit: function () {
      },
      FilesAdded: function (up, files) {
        uploader.start();
        return false;
      },
      BeforeUpload: function (up, file) {
        $(`#${btn}`).css('pointer-events', 'none');
      },
      // 上传进度
      UploadProgress: function (up, file) {
      },
      // 文件上传完毕
      FileUploaded: function (up, file, info) {
        $(`#${divId} .file-grid-2`).remove();
        if (info.status === 200) {
          var result = JSON.parse(info.response);
          if (result.code !== 0) {
            $(`#${divId}`).append(result.message);
          } else {
            let url = getFileServerJoinContextPath(result.data.url);
            $(`#${divId}`).val(url);
            window.$vueApp.item[name] = url;
            callback && callback(result.data);
          }
        } else {
          $(`#${divId}`).append(info.response);
        }
        $(`#${btn}`).css('pointer-events', '');
      },

      Error: function (up, err) {
        if (err.code === -600) {
          layer.msg('选择的文件太大了,不能超过' + fileMaxSize + 'M');
        } else if (err.code === -601) {
          layer.msg('只能上传' + fileExtensions + '格式大小的' + fileMaxSize);
        } else if (err.code === -602) {
          layer.msg('这个文件已经上传过一遍了');
        } else {
          layer.msg('上传异常');
        }
      }
    }
  });
  uploader.init();
  setTimeout(function () { $('.moxie-shim').css('top', 0); }, 500);
  return uploader;
}
